package com.example.zk.client;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;
import org.junit.internal.runners.JUnit4ClassRunner;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.Suite;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
 * Created by SOAL on 2017/7/9 0009.
 */
//@RunWith(SpringRunner.class)
//@RunWith(SpringJUnit4ClassRunner.class)
//@RunWith(Suite.class)
//@Suite.SuiteClasses(Runner.class)
public class SimpleZkClient extends Runner {

    public static final String connectString = "192.168.1.142:2181,192.168.1.140:2181,192.168.1.143:2181";
    public static final int sessionTimeout = 50000;
    public static final String parentNode = "/app1";

    ZooKeeper zkClent = null;

    @Before
    public void init() throws Exception {
        zkClent = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                //收到事件通知后回调函数（自己事件处理逻辑）
                System.out.println(watchedEvent.getType() + "----" + watchedEvent.getPath());
//                try {
//                    zkClent.getChildren("/",true);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
            }
        });
    }


    //创建节点
    @Test
    public void createNode ()throws Exception {
        //路径、参数、权限、类型
        String snode = zkClent.create("/ecclipse", "hellozk".getBytes()
                , ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

    }

    //获取子节点
    @Test
    public void getChildren() throws Exception {
        List<String> children =zkClent.getChildren("/",true);

        for (String child: children
             ) {
            System.out.println(child);
        }
        Thread.sleep(Long.MAX_VALUE); //保持监听，调用process方法
    }


    //判断是否存在
    @Test
    public void isExists() throws Exception {
        Stat stat= zkClent.exists("/ecclipse",false);
        System.out.println(stat==null?"not_exists":"exists");
        System.out.println(stat.getCtime());
    }



    //判断是否存在
    @Test
    public void getData() throws Exception {
       byte[] byt = zkClent.getData("/ecclipse",false,null);
        zkClent.setData("/ecclipse","ccc77".getBytes(),-1);
        System.out.println(new String(byt));
    }



    @Override
    public Description getDescription() {
        return null;
    }

    @Override
    public void run(RunNotifier runNotifier) {

    }
}
